package com.zhaopin.rpc.rpc08.server;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.zhaopin.rpc.ProductServiceImpl;
import com.zhaopin.rpc.UserServiceImpl;
import com.zhaopin.rpc.rpc08.common.HessianUtil;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static boolean running = true;
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(8888);
        while (running) {
            Socket s = ss.accept();
            process(s);
            s.close();
        }
        ss.close();
    }

    private static void process(Socket s) throws Exception {
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();

        Hessian2Input h2i = new Hessian2Input(in);
        Hessian2Output h2o = new Hessian2Output(out);

        String clazzName = h2i.readString();
        String methodName = h2i.readString();
        Class[] parameterTypes = (Class[])h2i.readObject();
        Object[] args = (Object[])h2i.readObject();

        Class clazz = null;

        //从服务器注册表找到具体的类
        clazz = getClassByClassName(clazzName);

        Method method = clazz.getMethod(methodName, parameterTypes);
        Object o = method.invoke(clazz.newInstance(), args);

        h2o.writeObject(HessianUtil.serialize(o));
        h2o.flush();
    }


    public static Class getClassByClassName(String className) throws ClassNotFoundException {
        if (Class.forName(className).isAssignableFrom(UserServiceImpl.class)){
            return UserServiceImpl.class;
        }
        if (Class.forName(className).isAssignableFrom(ProductServiceImpl.class)){
            return ProductServiceImpl.class;
        }

        return Object.class;
    }
}
